/*
	使用express.basicAuth中间件证用户名与密码
	使用数据库
*/

var express = require('express');
var mysql = require('mysql');
var app = express();

var pool = mysql.createPool({
	host: 'localhost',
	port: 3306,
	database: 'test',
	user : 'root',
	password: '123456'
});



app.use(express.basicAuth(function(user, pass, callback){
	pool.getConnection(function(err, connection){
		if(err) {
			connection.release();
			callback(null, false);
		}
		else{
			connection.query('select count(1) count from users where userName=? and passWord=?',
			[user, pass], 
			function(err, result){
				connection.release();
				if(result[0].count > 0){
					callback(null, true);
				}
				else{
					callback(null, false);
				}
			});
		}

	});
}));

app.get('/', function(req, res){
	res.send('你好');
});

app.listen(1337, 'localhost');